package com.example.sxt_practise.thread;

import java.util.Objects;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * A执行完,调用B,B调用完,调用C,c执行完调用A
 * @author gaofeng
 * @date 2022年06月02日 22:15
 */
public class ConditionTest {
    public static void main(String[] args) {
        Data3 data = new Data3() ;
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data.printA();
            }
        }, "A").start(); ;
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data.printB();
            }
        }, "B").start(); ;
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data.printC();
            }
        }, "C").start();

    }
}

class Data3 {

    private final Lock lock = new ReentrantLock() ;

    private final Condition condition1 = lock.newCondition();
    private final Condition condition2 = lock.newCondition();
    private final Condition condition3 = lock.newCondition();

    private Integer number = 1 ;

    public void printA() {
        lock.lock();
        try {
            while (!Objects.equals(number, 1)) {
                condition1 .await();
            }
            System.out.println(Thread.currentThread().getName() + " print AAA");
            number += 1;
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printB() {
        lock.lock();
        try {
            while (!Objects.equals(number, 2)) {
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName() + " print BBB");
            number += 1;
            condition3.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC() {
        lock.lock();
        try {
            while (!Objects.equals(number, 3)) {
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName() + " print CCC");
            number = 1;
            condition1.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
